package cn.ibizlab.modeling.groovy;

import groovy.transform.CompileStatic
import net.ibizsys.central.dataentity.action.DEActionRuntimeBase
import net.ibizsys.central.util.IEntityDTO
import net.ibizsys.runtime.util.KeyValueUtils
import net.ibizsys.central.dataentity.IDataEntityRuntime
import org.springframework.util.Assert

@CompileStatic
class InstallSysDEActionRuntime extends DEActionRuntimeBase{

    public GitRegisterDEActionRuntime() {
    }

    @Override
    protected Object onExecute(IEntityDTO iEntityDTO) throws Throwable {
        String psdevslnsysid = iEntityDTO.getString("psdevslnsysid","")
        String psdevslnid = iEntityDTO.getString("psdevslnid","")
        Assert.notNull(psdevslnsysid,"未传入系统标识")
        if(!psdevslnid) {
            this.getDataEntityRuntime().get(psdevslnsysid).copyTo(iEntityDTO)
            psdevslnid = iEntityDTO.getString("psdevslnid","")
        }
        String psdevslnname = iEntityDTO.getString("psdevslnname","")
        String psdevslnsysname = iEntityDTO.getString("psdevslnsysname","")

        IDataEntityRuntime wsDataEntityRuntime = this.getSystemRuntime().getDataEntityRuntime("DevCenter.PSDCWORKSPACE")
        //查找本方案内空闲生产线
        IEntityDTO ws = wsDataEntityRuntime.filter().eq("psdevslnid",psdevslnid).eq("assignstatus","20").nvl("psdevslnsysid").selectOne(true)
        if(!ws) {
            //查找全局空闲生产线
            ws = wsDataEntityRuntime.filter().eq("assignstatus", "20").nvl("psdevslnid").nvl("psdevslnsysid").selectOne(true)
            if(ws) {
                ws.set("psdevslnid",psdevslnid)
                ws.set("psdevslnname",psdevslnname)
                wsDataEntityRuntime.update(ws)
            }
        }
        if(!ws) {
            //查找其他方案中的空闲生产线
            ws = wsDataEntityRuntime.filter().eq("assignstatus", "20").ne("psdevslnid",psdevslnid).nvl("psdevslnsysid").selectOne(true)
            if(ws) {
                ws.set("psdevslnid",psdevslnid)
                ws.set("psdevslnname",psdevslnname)
                wsDataEntityRuntime.update(ws)
            }
        }
        if(ws) {
            ws.set("psdevslnsysid",psdevslnsysid)
            ws.set("psdevslnsysname",psdevslnsysname)
            wsDataEntityRuntime.executeAction("InstallSys", null, [ws] as Object[])
        }
        else {
            throw new Exception("未找到空闲的生产线，安装失败");
        }
        this.getDataEntityRuntime().get(psdevslnsysid).copyTo(iEntityDTO)
        return iEntityDTO
    }


}